package com.niodata.dp.monitor.base;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

/**
 * Created by ndp on 17-9-12.
 */
@Component
public class CrossOriginFilter implements Filter {

  /**
   * do filter.
   *
   * @param req request
   * @param res response
   * @param chain filter chain
   * @throws IOException exception
   * @throws ServletException exception
   */
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    StringBuilder sb = new StringBuilder();
    sb.append("Origin").append(",");
    sb.append("No-Cache").append(",");
    sb.append("X-Requested-With").append(",");
    sb.append("If-Modified-Since").append(",");
    sb.append("Pragma").append(",");
    sb.append("Last-Modified").append(",");
    sb.append("Cache-Control").append(",");
    sb.append("Expires").append(",");
    sb.append("Content-Type").append(",");
    sb.append("X-E4M-With");

    response.setHeader("Access-Control-Allow-Headers", sb.toString());
    chain.doFilter(req, res);
  }

  public void init(FilterConfig filterConfig) {
  }

  public void destroy() {
  }
}